<!-- 用户相关 -->
<template>
  <div class="app-container">
    <div class="invitation-filterhead">
      <el-form :inline="true" :model="form" ref="form">
        <el-form-item label="UID：" prop="UID">
          <el-input
            placeholder="请输入UID"
            prefix-icon="el-icon-search"
            v-model="form.UID">
          </el-input>
        </el-form-item>
        <el-form-item label="手机号：" prop="cellPhoneNumber">
          <el-input
            placeholder="请输入手机号"
            prefix-icon="el-icon-search"
            v-model="form.cellPhoneNumber">
          </el-input>
        </el-form-item>
        <el-form-item label="用户昵称：" prop="userName">
          <el-input
            placeholder="请输入用户昵称"
            prefix-icon="el-icon-search"
            v-model="form.userName">
          </el-input>
        </el-form-item>
        <el-form-item label="所在省份：" prop="provinces">
          <el-select
            placeholder="请选择所在省份"
            prefix-icon="el-icon-search"
            v-model="form.provinces">
            <el-option
              v-for="item in provinceList"
              :key="item.id"
              :label="item.name"
              :value="item.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">筛选</el-button>
          <el-button @click="onCancel()">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-box">
      <el-button class="add-activity" type="primary" @click="addInBlack()">加入黑名单</el-button>
      <el-button class="add-activity" type="primary" @click="addInLabelGroup()">加入标签组</el-button>
      <el-button class="add-activity" type="primary" @click="creatLabelGroup()">创建标签组</el-button>
      <el-table :data="tableData" v-loading="tableLoading">
        <el-table-column label="序号" type="index" :index="indexMethod" />
        <el-table-column prop="id" label="uid" />
        <el-table-column prop="mobile" label="手机号" />
        <el-table-column prop="name" label="用户昵称" />
        <el-table-column prop="provinceName" label="所在省份" />
        <el-table-column prop="tagName" label="所属标签组" />
        <el-table-column prop="blackName" label="所属黑名单" />
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-button @click="viewDetails(scope.row)" type="text" size="small">查看详情</el-button>
            <el-button @click="removesTab(scope.row)" type="text" size="small">从标签组移除</el-button>
            <el-button @click="removesBlack(scope.row)" type="text" size="small">从黑名单移除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <InBody v-show="total>0">
      <pagination
        :total="total"
        :page.sync="form.pageNum"
        :limit.sync="form.pageSize"
        @pagination="queryUserList" />
    </InBody>
    <el-dialog
      title="提示"
      :visible.sync="creatLableGroupVisible"
      width="30%"
      :before-close="boxCloseBefore"
      destroy-on-close
    >
      <el-form :model="userForm" ref="userForm" :inline="true" label-position="right" :rules="rules" label-width="92px">
        <el-form-item label="标签组名称" prop="addLableName" v-if="this.labelDialogType === 1">
          <el-input
            placeholder="请输入标签组名称"
            v-model="userForm.addLableName"
            maxlength="20"
          />
        </el-form-item>
        <el-form-item label="选择标签组" prop="tagIdList" v-if="this.labelDialogType === 2 || this.labelDialogType === 4">
          <el-select
            placeholder="请选择"
            prefix-icon="el-icon-search"
            multiple
            v-model="userForm.tagIdList">
            <el-option
              v-for="item in userTagList"
              :key="item.id || item.tagId"
              :label="item.tagName"
              :value="item.id || item.tagId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择黑名单" prop="blackTypeId" v-if="this.labelDialogType === 3 || this.labelDialogType === 5">
          <el-select
            placeholder="请选择"
            prefix-icon="el-icon-search"
            :multiple = "this.labelDialogType === 5"
            v-model="userForm.blackTypeId">
            <el-option
              v-for="item in userBlackList"
              :key="item.type"
              :label="item.name"
              :value="item.type">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="人群" prop="userIds" v-if="this.labelDialogType === 2 || this.labelDialogType === 3">
          <div>
            <el-input type="textarea" :rows="2" v-model="userForm.userIds" placeholder="输入uid 每行一个 回车隔开" />
            <div class="upload-container">
              <label for="file-upload" class="custom-upload-button">
                <i class="el-icon-upload2"></i> 上传文件
              </label>
              <input type="file" id="file-upload" style="display: none;" @change="changeFile">
            </div>
          </div>
        </el-form-item>
        <div style="margin-top: 20px; text-align: center">
          <el-form-item>
            <el-button
              type="primary"
              @click="onEditSubmit('userForm')"
            >
              提交
            </el-button>
          </el-form-item>
        </div>
      </el-form>
    </el-dialog>
    <el-dialog title="用户详情" :visible.sync="userViewStatus" fullscreen>
      <el-form label-position="right" label-width="100px">
        <el-form-item label="uid">
          {{ detail.id }}
        </el-form-item>
        <el-form-item label="手机号">
          {{ detail.mobile }}
        </el-form-item>
        <el-form-item label="用户昵称">
          {{ detail.name }}
        </el-form-item>
        <el-form-item label="所在省份">
          {{ detail.provinceName || '无' }}
        </el-form-item>
        <el-form-item label="所属标签组">
          {{ detail.tagName || '无' }}
        </el-form-item>
        <el-form-item label="所属黑名单">
          {{ detail.blackName || '无' }}
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { ref } from "vue";
import { mapGetters } from "vuex";
import {
  queryUserInfoList,
  queryUserByList,
  userRelList,
  addUserRel,
  deleteUserRel,
  getBlackList,
  addBlack,
  removeBlack,
  queryProvince
} from '@/api/user/user';

export default {
  computed: {
    ...mapGetters(['user']),
  },
  data() {
    return {
      form: {
        UID: '',
        cellPhoneNumber: '',
        userName: '',
        provinces: '',
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      provinceList: '',
      tableLoading: false,
      tableData: [],
      labelDialogType: 0,
      creatLableGroupVisible: false, // 创建标签组弹框
      addLableGroupVisible: false, // 加入标签组弹框
      addBlackVisible: false, // 加入黑名单弹框
      creatLabelGroupId: '', // 标签组名称
      userTagList: [],
      userBlackList: [],
      userForm: { // 弹框直接共有一套
        addLableName: '',
        tagIdList: '',
        userIds: [],
        blackTypeId: '', // 黑名单
      },
      rules: {
        addLableName: [
          { required: true, message: '请输入标签组名称', trigger: 'blur' },
          { pattern: /^[\u4e00-\u9fa5\d]*$/, message: '请输入正确格式,中文和数字' }
        ],
        tagIdList: [{ required: true, message: '请选择标签组', trigger: 'blur' }],
        userIds: [{ required: true, message: '请填写人群', trigger: 'blur' }],
        blackTypeId: [{ required: true, message: '请选择黑名单', trigger: 'blur' }],
      },
      selectDataInfo: '',
      userViewStatus: false,
      detail: '',
    }
  },
  mounted() {
    this.queryProvinceList()
    this.queryUserList()
  },
  methods: {
    queryProvinceList() {
      queryProvince({pid: 0}).then(res => {
        if (res.code === 200) {
          this.provinceList = res.data;
        }
      })
    },
    queryUserList() {
      this.tableLoading = true;
      queryUserInfoList({
        id: this.form.UID,
        name: this.form.userName,
        mobile: this.form.cellPhoneNumber,
        provinceName: this.form.provinces
      }).then(res => {
        if (res.code === 200) {
          this.tableData = res.rows;
          this.total = +res.total;
        }
        this.tableLoading = false;
      })
    },
    onCancel() {
      this.form = {
        UID: '',
        cellPhoneNumber: '',
        userName: '',
        provinces: '',
      }
      this.queryUserList();
    },
    onSubmit() {
      this.queryUserList()
    },
    indexMethod(index) {
      return index + 1;
    },
    // 创建标签组
    creatLabelGroup() {
      this.labelDialogType = 1;
      this.creatLableGroupVisible = true;
    },
    // 加入标签组
    addInLabelGroup() {
      this.getUserRelList();
      this.labelDialogType = 2;
      this.creatLableGroupVisible = true;
    },
    // 加入黑名单
    addInBlack() {
      this.getUserBlackList();
      this.labelDialogType = 3;
      this.creatLableGroupVisible = true;
    },
    // 获取标签组
    getUserRelList() {
      userRelList().then(res => {
        if (res.code === 200) {
          this.userTagList = res.data
        }
      })
    },
    // 获取黑名单组
    getUserBlackList() {
      getBlackList().then(res => {
        if (res.code === 200) {
          this.userBlackList = res.data
        }
      })
    },
    // 查看详情
    viewDetails(row) {
      // this.queryUserByListFn(row.id);
      this.$router.push({path: '/user/detail', query: { id: row.id }})
    },
    queryUserByListFn(userId) {
      queryUserByList({
        userId
      }).then(res => {
        if (res.code === 200) {
          console.log('resss', res)
          this.detail = res.data;
          this.userViewStatus = true;
        }
      })
    },
    // 从标签组移除
    removesTab(row) {
      this.selectDataInfo = row;
      // this.userTagList = row.tagList.map((item) => {
      //   item.id = item.tagId;
      //   return item;
      // });
      this.userTagList = row.tagList;
      this.labelDialogType = 4;
      this.creatLableGroupVisible = true;
    },
    // 从黑名单移除
    removesBlack(row) {
      this.selectDataInfo = row;
      this.userBlackList = row.blackList;
      this.labelDialogType = 5;
      this.creatLableGroupVisible = true;
    },
    onEditSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(this.labelDialogType == 1 || this.labelDialogType == 2) return this.addUserRelApiFn();
          if(this.labelDialogType == 3) this.addBlackApiFn();
          if(this.labelDialogType == 4 || this.labelDialogType == 5) {
            this.$confirm('是否移除')
            .then(_ => {
              if(this.labelDialogType == 4) this.deleteUserRelApiFn();
              if(this.labelDialogType == 5) this.removeBlackApiFn();
            })
            .catch(_ => {
              this.bigBoxLoading = false;
            });
          }
        } else {
          return false;
        }
      });
    },
    // 新增标签组、新增用户标签组关系
    addUserRelApiFn() {
      const params = {};
      if(this.labelDialogType == 1) params.tagName = this.userForm.addLableName;
      if(this.labelDialogType == 2) {
        const userIdsArr = this.userForm.userIds.split('\n');
        params.tagIdList = this.userForm.tagIdList;
        params.userIds = userIdsArr.filter(item => item);
      }
      addUserRel(params).then(res => {
        if (res.code === 200) {
          this.$message({
            message: '操作成功',
            type: 'success'
          });
          // this.creatLableGroupVisible = false;
          this.boxCloseBefore()
          this.queryUserList()
        }
      })
    },
    // 添加黑名单
    addBlackApiFn() {
      const userIdsArr = this.userForm.userIds.split('\n');
      const params = {
        blackTypeId: this.userForm.blackTypeId,
        userIds: userIdsArr.filter(item => item)
      };
      addBlack(params).then(res => {
        if (res.code === 200) {
          this.$message({
            message: '操作成功',
            type: 'success'
          });
          // this.creatLableGroupVisible = false;
          this.boxCloseBefore();
          this.queryUserList()
        }
      })
    },
    // 自定义人群选择文件
    changeFile(event) {
      const XLSX = require('xlsx');
      const file = event.target.files[0];
      const reader = new FileReader();
      reader.onload = (e) => {
        const data = new Uint8Array(e.target.result);
        const workbook = XLSX.read(data, { type: 'array' });
        const sheetName = workbook.SheetNames[0]; // 获取第一个工作表的名称
        const sheet = workbook.Sheets[sheetName]; // 获取工作表数据
        const jsonData = XLSX.utils.sheet_to_json(sheet, { header: 1 });
        this.userForm.userIds = jsonData.flat().join('\n')
      };
      reader.readAsArrayBuffer(file)
    },
    // 将用户从标签组移除
    deleteUserRelApiFn() {
      deleteUserRel({
        tagIdList: this.userForm.tagIdList,
        userId: this.selectDataInfo.id
      }).then(res => {
        if (res.code === 200) {
          this.$message({
            message: '操作成功',
            type: 'success'
          });
          // this.creatLableGroupVisible = false;
          this.boxCloseBefore();
          this.queryUserList()
        }
      })
    },
    // 删除黑名单
    removeBlackApiFn() {
      removeBlack({
        blackTypeIds: this.userForm.blackTypeId,
        userId: this.selectDataInfo.id
      }).then(res => {
        if (res.code === 200) {
          this.$message({
            message: '操作成功',
            type: 'success'
          });
          // this.creatLableGroupVisible = false;
          this.boxCloseBefore();
          this.queryUserList()
        }
      })
    },
    boxCloseBefore() {
      this.resetForm('userForm');
      this.userForm = {
        addLableName: '',
        tagIdList: '',
        userIds: [],
        blackTypeId: '', // 黑名单
      }
      this.creatLableGroupVisible = false;
      this.selectDataInfo = '';
      this.userTagList = [];
      this.userBlackList = [];
    },
  }
}
</script>

<style scoped lang="scss">
.table-box {
  .add-activity {
    float: right;
    margin: 10px;
  }
  .table-switch {
    margin-right: 10px;
  }
}
.big-box {
  width: 100%;
  height: 100%;
  background: #fff;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
  display: flex;
  padding: 10px;
  justify-content: center;
  .el-form {
    width: 500px;
  }
  .bigbox-line {
    // border-bottom: 1px solid #dcdcdc;
    padding: 10px;
    .bigbox-lable {
      font-size: 14px;
      font-weight: bold;
    }
    .rules-list {
      display: flex;
      flex-direction: column;
      margin-bottom: 10px;
      .rules-item {
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 10px 0;
        .user-stairs {

        }
        .user-input {
          display: flex;
          align-items: center;
          margin: 0 10px;
          .el-input {
            flex: 1;
            margin-right: 5px;
          }
        }
        .user-select {
          display: flex;
          align-items: center;
          margin: 0 10px;
          .el-select {
            flex: 1;
            margin-right: 5px;
          }
        }
        .user-reward {

        }
      }
    }
    .rules-edit {
      color: #1890ff;
      font-weight: bold;
      cursor: pointer;
    }
    .go-file {
      width: 200px;
      min-height: 160px;
      border: 1px dashed #dcdcdc;
      display: flex;
      align-items: center;
      flex-direction: column;
      justify-content: center;
      font-size: 12px;
      line-height: 16px;
      margin-top: 10px;
    }
    .file {
      width: 200px;
      height: auto;
      margin-top: 10px;
    }
  }
  .close-box {
    font-size: 20px;
    cursor: pointer;
  }
}
</style>
